package com.qingsong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qingsong.dto.*;
import com.qingsong.entity.Assets;
import com.qingsong.exception.ServiceException;
import com.qingsong.mapper.PermissionMapper;
import com.qingsong.mapper.AssetsMapper;
import com.qingsong.service.AssetsService;
import com.qingsong.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author qingsong
 */
@Service
@CacheConfig(cacheNames = "assets")
public class AssetsServiceImpl implements AssetsService {

    @Autowired
    private AssetsMapper assetsMapper;

    @Autowired
    private PermissionMapper permissionMapper;


    @CacheEvict(allEntries = true)
    @Override
    public int insert(AssetsInsertDTO assetsInsertDTO) {
        Assets assets = BeanUtil.copyProperties(assetsInsertDTO,Assets.class);
        assets.setDeleted(0);
        assets.setPicture("default-avatar.png");
        assets.setCreated(LocalDateTime.now());
        assets.setUpdated(LocalDateTime.now());
        int result = assetsMapper.insert(assets);
        if(result <= 0){
            throw new ServiceException("数据库添加失败!");
        }
        return result;
    }

    @Cacheable(key = "#id", condition = "#id != null", unless = "#result == null")
    @Override
    public Assets selectById(Long id) {
        Assets result = assetsMapper.selectById(id);
        if(ObjectUtil.isEmpty(result)){
            throw new ServiceException("ID不存在!");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int updateById(AssetsUpdateDTO assetsUpdateDTO) {
        Assets assets = BeanUtil.copyProperties(assetsUpdateDTO, Assets.class);

        // 设置默认值
        assets.setCreated(null);
        assets.setUpdated(LocalDateTime.now());
        // DB修改
        int result = assetsMapper.updateById(assets);
        if (result <= 0) {
            throw new ServiceException("DB修改失败");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int logicDeleteById(Long id) {
        // todo 查询该记录是否被引用
        int result = assetsMapper.logicDeleteById(id);
        if(result <= 0){
            throw new ServiceException("数据库逻辑删除失败!");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int logicDeleteByIds(List<Long> ids) {
        int result = assetsMapper.logicDeleteByIds(ids);
        if(result <= 0){
            throw new ServiceException("数据库批量逻辑删除失败!");
        }
        return result;
    }

    @CacheEvict(allEntries = true)
    @Override
    public String uploadPicture(AssetsUploadDTO dto) {

        final String DIR = "avatar";
        final String BUCKET_NAME = "start";
        MultipartFile avatarFile = dto.getPictureFile();
        Long id = dto.getId();

        //DB查询
        Assets assets = assetsMapper.selectById(id);
        if(ObjectUtil.isNull(assets)){
            throw new ServiceException("该资产不存在");
        }
        //从MINIO中删除旧文件,默认头像不删除
        String oldAvatar = assets.getPicture();
        if(!("defult-avatar.png".equals(oldAvatar))){
            MinioUtil.delete(oldAvatar, DIR, BUCKET_NAME);
        }
        // 将文件上传到MINIO中
        String newAvatar = MinioUtil.randomFilename(avatarFile);
        MinioUtil.upload(avatarFile, newAvatar, DIR, BUCKET_NAME);

        // DB修改
        assets.setPicture(newAvatar);
        if (assetsMapper.updateById(assets) <= 0) {
            throw new ServiceException("DB修改失败");
        }
        return newAvatar;
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null ")
    @Override
    public List<Assets> list() {
        return assetsMapper.list();
    }

    @Cacheable(key = "#root.methodName + ':' + " + "#pageDTO.getPageNum() + ':' + " + "#pageDTO.getPageSize()", unless = "#result == null ")
    @Override
    public PageInfo<Assets> page(PageDTO pageDTO) {
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
        return new PageInfo<>(assetsMapper.list());
    }

    @Cacheable(key = "#root.methodName + ':' + " +
            "#dto.getTitle() + ':' + " +
            "#dto.getPageNum() + ':' + " +
            "#dto.getPageSize()", unless = "#result == null ")
    @Override
    public PageInfo<Assets> pageLikeTitle(AssetsPageDTO dto) {
        //开启分页
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        //数据分页
        return new PageInfo<>(assetsMapper.listLikeTitle(dto.getTitle()));
    }
}
